package com.smartcar.controller;

import com.smartcar.dto.ApiResponse;
import com.smartcar.dto.NetworkConfigRequest;
import com.smartcar.tcp.TCPClientManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.concurrent.CompletableFuture;

/**
 * 网络配置控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/network")
@CrossOrigin(origins = "*")
public class NetworkController {

    private final TCPClientManager tcpClientManager;

    public NetworkController(TCPClientManager tcpClientManager) {
        this.tcpClientManager = tcpClientManager;
    }

    /**
     * 配置网络连接
     */
    @PostMapping("/config")
    public ApiResponse<Boolean> configNetwork(@Valid @RequestBody NetworkConfigRequest request) {
        try {
            // 初始化网络地址
            tcpClientManager.initNetAddress(request.getIp(), request.getTcpPort());
            
            // 尝试连接
            CompletableFuture<Boolean> connectFuture = tcpClientManager.connect();
            Boolean success = connectFuture.get();
            
            if (success) {
                log.info("网络连接成功: {}:{}", request.getIp(), request.getTcpPort());
                return ApiResponse.success(true);
            } else {
                log.error("网络连接失败: {}:{}", request.getIp(), request.getTcpPort());
                return ApiResponse.error("网络连接失败");
            }
        } catch (Exception e) {
            log.error("网络配置失败", e);
            return ApiResponse.error("网络配置失败: " + e.getMessage());
        }
    }

    /**
     * 获取连接状态
     */
    @GetMapping("/status")
    public ApiResponse<Boolean> getConnectionStatus() {
        try {
            boolean isConnected = tcpClientManager.isConnected();
            return ApiResponse.success(isConnected);
        } catch (Exception e) {
            log.error("获取连接状态失败", e);
            return ApiResponse.error("获取连接状态失败: " + e.getMessage());
        }
    }

    /**
     * 断开连接
     */
    @PostMapping("/disconnect")
    public ApiResponse<Void> disconnect() {
        try {
            tcpClientManager.disconnect();
            return ApiResponse.success();
        } catch (Exception e) {
            log.error("断开连接失败", e);
            return ApiResponse.error("断开连接失败: " + e.getMessage());
        }
    }
} 